package plus.easydo.server.user.mp.controller;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import plus.easydo.core.result.R;
import plus.easydo.server.user.mp.constant.UserConstants;
import plus.easydo.server.user.mp.entity.SysRole;
import plus.easydo.server.user.mp.entity.SysUser;
import plus.easydo.server.user.mp.qo.UserQo;
import plus.easydo.server.user.mp.service.ISysPermissionService;
import plus.easydo.server.user.mp.service.ISysPostService;
import plus.easydo.server.user.mp.service.ISysRoleService;
import plus.easydo.server.user.mp.service.ISysUserService;
import plus.easydo.server.user.mp.vo.UserVo;
import plus.easydo.starter.log.annotation.SystemLog;
import plus.easydo.starter.mybatis.plus.base.MPBaseController;
import plus.easydo.starter.mybatis.plus.result.MPDataResult;
import plus.easydo.starter.oauth.resources.anotation.CustomizePreAuthorize;
import plus.easydo.starter.oauth.core.utils.Oauth2Utils;
import plus.easydo.starter.oauth.resources.anotation.IgnoreThePermissions;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Api("用户信息")
@RestController
@RequestMapping("/user")
public class SysUserController extends MPBaseController {
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysPostService postService;

    @Resource
    private ISysPermissionService permissionService;

    @PreAuthorize("hasScope('oauth-server')")
    @RequestMapping("/findByUserName")
    public R<SysUser> findByUserName(String userName) {
        SysUser user = userService.selectUserByUserName(userName);
        if (user == null) {
            return null;
        }
        Long userId = user.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        user.setRoleSet(roles);
        user.setPermissions(permissions);
        if("e".equals(userName)){
            throw new NullPointerException();
        }
        return ok(user);
    }

    /**
     * 更换头像
     *
     * @return plus.easydo.core.result.R
     * @author laoyu
     * @date 2021/11/12
     */
    @IgnoreThePermissions
    @RequestMapping("/profile/avatar")
    public R<SysUser> avatar(@RequestParam(name = "avatarfile", required = false) MultipartFile avatarfile) {
        return opResult(userService.avatar(avatarfile));
    }


    /**
     * 获取用户列表
     */
    @CustomizePreAuthorize(hasPermission = {"system:user:list"})
    @PostMapping("/page")
    public MPDataResult page(@RequestBody UserQo qo) {
        IPage<UserVo> page = userService.page(qo);
        return ok(page);
    }

//    @PreAuthorize("hasPermission('system:user:export")
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, SysUser user) throws IOException
//    {
//        List<SysUser> list = userService.selectUserList(user);
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        util.exportExcel(response, list, "用户数据");
//    }
//
//    @PreAuthorize("hasPermission('system:user:import")
//    @PostMapping("/importData")
//    public rResult importData(MultipartFile file, boolean updateSupport) throws Exception
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        List<SysUser> userList = util.importExcel(file.getInputStream());
//        String operName = SecurityUtils.getUsername();
//        String message = userService.importUser(userList, updateSupport, operName);
//        return rResult.success(message);
//    }

//    @PostMapping("/importTemplate")
//    public void importTemplate(HttpServletResponse response) throws IOException
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        util.importTemplateExcel(response, "用户数据");
//    }

//    /**
//     * 获取当前用户信息
//     */
//    @GetMapping("/info/{username}")
//    public R<LoginUser> info(@PathVariable("username") String username)
//    {
//        SysUser sysUser = userService.selectUserByUserName(username);
//        if (StringUtils.isNull(sysUser))
//        {
//            return R.fail("用户名或密码错误");
//        }
//        // 角色集合
//        Set<String> roles = permissionService.getRolePermission(sysUser.getUserId());
//        // 权限集合
//        Set<String> permissions = permissionService.getMenuPermission(sysUser.getUserId());
//        LoginUser sysUserVo = new LoginUser();
//        sysUserVo.setSysUser(sysUser);
//        sysUserVo.setRoles(roles);
//        sysUserVo.setPermissions(permissions);
//        return R.ok(sysUserVo);
//    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Map<String, Object> getInfo() {
        Long userId = Oauth2Utils.getUserIdLong();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        Map<String, Object> map = new HashMap<>(4);
        map.put("user", userService.selectUserById(userId));
        map.put("roles", roles);
        map.put("permissions", permissions);
        return map;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("hasPermission('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public  Map<String, Object> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        List<SysRole> roles = roleService.selectRoleAll();
        Map<String, Object> map = new HashMap<>(4);
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(role -> !role.isAdmin()).collect(Collectors.toList()));
        map.put("posts", postService.selectPostAll());
        if (Objects.nonNull(userId)) {
            map.put("data", userService.selectUserById(userId));
            map.put("postIds", postService.selectPostListByUserId(userId));
            map.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return map;
    }

    /**
     * 新增用户
     */
    @SystemLog(value = "新增用户",saveLog = true)
    @PreAuthorize("hasPermission('system:user:add')")
    @PostMapping
    public R<Object> add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (CharSequenceUtil.isNotEmpty(user.getPhoneNumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (CharSequenceUtil.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(Oauth2Utils.getUserName());
        user.setPassword(Oauth2Utils.encryptPassword(user.getPassword()));
        return opResult(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @SystemLog(value = "修改用户",saveLog = true)
    @PreAuthorize("hasPermission('system:user:edit')")
    @PutMapping
    public R<Object> edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (CharSequenceUtil.isNotEmpty(user.getPhoneNumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (CharSequenceUtil.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(Oauth2Utils.getUserName());
        return opResult(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @SystemLog(value = "删除用户",saveLog = true)
    @PreAuthorize("hasPermission('system:user:remove')")
    @DeleteMapping("/{userIds}")
    public R<Object> remove(@PathVariable Long[] userIds) {
        return opResult(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @SystemLog(value = "重置密码",saveLog = true)
    @PreAuthorize("hasPermission('system:user:edit')")
    @PutMapping("/resetPwd")
    public R<Object> resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(Oauth2Utils.encryptPassword(user.getPassword()));
        user.setUpdateBy(Oauth2Utils.getUserName());
        return opResult(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @SystemLog(value = "用户状态修改",saveLog = true)
    @PreAuthorize("hasPermission('system:user:edit')")
    @PutMapping("/changeStatus")
    public R<Object> changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(Oauth2Utils.getUserName());
        return opResult(userService.updateUserStatus(user));
    }
}
